import mongoose from './mongoose'
import { ObjectId, Date, Number } from 'mongoose'
import lastModifiedPlugin from './mongoosePlugins/lastModPlugin'

const Types = mongoose.Schema.Types

export class UserModel {
  id?: ObjectId
  username: string
  password: string
  email: string
  createTime?: Date
  avatar?: Buffer
  state?: Number
  versionTable: string
  accountTable: string
}

const user = new mongoose.Schema({
  id: Types.ObjectId,
  username: {
    type: Types.String,
    required: true,
    unique: true,
    index: 1,
    maxlength: 32,
    match: /[a-zA-Z0-9]{5}/ // 用户名只能包含大小写字母以及数字 长度5-20
  },
  password: {
    type: Types.String,
    required: true
  },
  email: {
    type: Types.String,
    required: true,
    unique: true,
    index: 1,
    maxlength: 64,
    match: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/
  },
  createTime: {
    type: Types.Date,
    default: Date.now,
    index: 1
  },
  avatar: { // 用户头像
    type: Types.Buffer
  },
  state: { // 用户状态
    type: Types.Number,
    default: 0
    /*
     * -1 邮箱未激活
     * 0  正常用户
     */
  },
  versionTable: { // 记录此用户的 version table, 以此支持多用户
    type: Types.String,
    required: true,
    unique: true,
    index: 1,
    maxlength: 64
  },
  accountTable: { // 记录此用户的 account table, 以此支持多用户
    type: Types.String,
    required: true,
    unique: true,
    index: 1,
    maxlength: 64
  }
})

user.plugin(lastModifiedPlugin)

export default mongoose.model('User', user, 'user')
